import {
    Button,
    Card,
    Col,
    Divider,
    Empty,
    Image,
    List,
    Menu, Modal, Rate,
    Row,
    Spin,
    Statistic,
    Table,
} from "antd";
import React from "react";
import {Component} from "react";
import {
    GET_CHAPTER_DETAILES, GET_CHECK_ILAB_LOGIN,
    GET_COURSE_DOCS, GET_COURSE_RECORD,
    GET_COURSE_TEACHERS, GET_DATA_DETAILES, GET_RATE_DETAILES, GET_SCORE_DETAILES, GET_STUDY_RECORD,
    GET_VR_RECORD, POST_ILAB_LOGIN, POST_RATE_DETAILES,
    POST_TICKET_LOGIN,
    SERVER_PICTURE_URL, USER_LOGIN,
} from "../../api/APIURLDefine";
import {AxioInstance} from "../../api/AxiosHelper";
import {model} from "../../model/model";
import "./index.less";
import Avatar from "antd/lib/avatar/avatar";
import {Chart} from "@antv/g2";
import $ from "jquery";
import DPlayer from "react-dplayer";
import {
    CheckUserAuthorized,
    CheckUserLogin,
    CheckUserLoginByThink,
    CheckUserLoginOnly, FormatTime,
    setRichTextImage
} from "../../utils/Utils";
import AuthenticateModal from "../../components/authenticateModal";
import CommentBox from "../../components/comments/CommentBox";
import CommentItem from "../../components/comments/CommentItem";
import {inject, observer} from "mobx-react";
import moment from "moment";
import {LoginType} from "../../stores/GlobalStore";
import Store from "../../stores";
import ButtonGroup from "antd/es/button/button-group";

interface VRExpState {
    lessonDara?: model.VRLessonDetailes;
    chapterId: number;
    currentSelect: number;
    teachers: Array<any>;
    docs: Array<any>;
    record: any;
    waitNum: number;
    visible: boolean;
    expandID: number;
    currentId: number;
    starIndex: number;
    point: number;
    studyRecord: any;
    isModalVisible: boolean;
    time: any;
    isWait: boolean;
    score: any;
}

const PermissionFC: React.FC<any> = (props: any) => {
    return <div>{props.children}</div>;
};


@inject("globalStore", "userStore", "commentStore")
@observer
class VRExp extends Component<any, VRExpState> {
    constructor(props: any) {
        super(props);
        this.state = {
            lessonDara: null,
            chapterId: 0,
            currentSelect: 0,
            teachers: [],
            docs: [],
            record: null,
            waitNum: 0,
            visible: false,
            expandID: -1,
            currentId: -1,
            starIndex: 0,
            point: 0,
            studyRecord: [],
            isModalVisible: false,
            time: {},
            score: {},
            isWait: false
        };
    }

    componentWillMount() {
        //清空专家账号
        this.props.userStore.setTestAccount(null);
        this.props.userStore.setTestPwd(null);
    }

    componentDidMount() {
        var params = new URLSearchParams(this.props.history.location.search);
        var id = 1;
        let token = "";
        if (params.has("id")) {
            id = parseInt(params.get("id"));
            console.log(id);
        }
        // this.props.commentStore.SetCourseId(id);
        AxioInstance.get(`${GET_CHAPTER_DETAILES}/${id}`).then((data: any) => {
            this.setState({lessonDara: data.lessonDetails});
            let courseId = data.lessonDetails?.courseId;
            let examId = data.lessonDetails?.id;
            this.props.commentStore.SetCourseId(courseId);
            if (params.has("ticket")) {
                token = params.get("ticket");
                const data = {
                    course: courseId,
                    ticket: encodeURIComponent(token)
                };
                AxioInstance.post(`${POST_TICKET_LOGIN}`, JSON.stringify(data)).then((resp: any) => {
                    console.log(resp);
                    this.props.userStore.setAccessToken(resp.access_token);
                }).catch(e => console.error(e));
                // this.props.userStore.setAccessToken(token);
            }
            if (data.lessonDetails.testAccount && data.lessonDetails.testPwd) {
                this.props.userStore.setTestAccount(data.lessonDetails.testAccount);
                this.props.userStore.setTestPwd(data.lessonDetails.testPwd);
            }
            if (data.lessonDetails) {
                this.getStudyRecord(1, 10, data.lessonDetails.id);
            }
            setTimeout(() => {
                let fieldName = `course-${data.lessonDetails.chapterId}-${this.props.userStore.userInfo?.id}`;
                let star = window.localStorage.getItem(fieldName);
                if (star && Number(star) > 0) {
                    this.setState({point: Number(star)});
                }
            }, 100)
            AxioInstance.get(`${GET_DATA_DETAILES}/${examId}`).then((data: any) => {
                this.setState({time: data});
            }).catch((e) => {
                console.error(e);
            });
            AxioInstance.get(`${GET_RATE_DETAILES}/${examId}`).then((data: any) => {
                let point = Math.round(data);
                if (isNaN(point)) {
                    point = 0;
                }
                this.setState({point});
            }).catch((e) => {
                console.error(e);
            });
            AxioInstance.get(`${GET_SCORE_DETAILES}/${examId}`).then((data: any) => {
                this.setState({score: data});
            }).catch((e) => {
                console.error(e);
            });
            AxioInstance.get(`${GET_COURSE_TEACHERS}/${data.courseId}`).then(
                (data: any) => {
                    this.setState({teachers: data});
                }
            );
            if (data.lessonDetails) {
                AxioInstance.get(`${GET_COURSE_DOCS}/${data.lessonDetails.id}`).then((data: any) => {
                    // console.log(data);
                    this.setState({docs: data})
                }).catch(e => console.error(e))
                AxioInstance.get(`${GET_VR_RECORD}/${data.lessonDetails.id}`).then((resp) => {
                    this.setState({record: resp});
                }).catch(e => console.error(e));
            }

        }).catch((e) => console.error(e));
        //GET_VR_RECORD  todo 接口替换


    }

    private getStudyRecord = (page, pageSize, id) => {
        AxioInstance.get(`${GET_STUDY_RECORD}/${page}/${pageSize}?id=${id}`).then((resp: any) => {
            this.setState({studyRecord: resp});
        }).catch((e) => console.error(e));
    }
    private submitRate = (value) => {
        const {lessonDara} = this.state;
        const rate = {
            expId: lessonDara.id,
            rate: Math.round(value)
        }
        const json = JSON.stringify(rate);
        AxioInstance.post(`${POST_RATE_DETAILES}/${lessonDara.id}`, json).then((resp: any) => {
            console.log(resp);
        }).catch((e) => console.error(e));
    }

    private rendDescription() {
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_1.png"></img>
                    <span>项目介绍</span>
                </div>
                <div
                    className="rich-content"
                    dangerouslySetInnerHTML={{
                        __html: setRichTextImage(this.state.lessonDara?.description),
                    }}
                    style={{marginTop: "0.1rem"}}
                />
            </div>
        );
    }

    changeIndex(index: number) {
        let count = index || this.state.point;
        let stars = $("#star-container").children("a");
        stars.each(((ind, element) => {
            element.className = parseInt(element.innerHTML) <= count ? "select" : "";
        }));
        this.setState({starIndex: count});
    }

    renderStar = () => {
        const {starIndex} = this.state;
        return <div style={{width: "100%", height: "100%", paddingLeft: "0.35rem"}}>
            <div style={{
                fontSize: "0.16rem",
                color: "#333333",
                textAlign: "left",
                fontWeight: "bold",
                //width:"auto"
            }}>
                实验评价
            </div>
            <div style={{
                textAlign: "left",
                fontSize: "0.48rem",
                color: "#dd5303",
                fontWeight: "bold",
                height: "0.6rem"
            }}>
                {this.state.point}
            </div>
            <div style={{display: "flex", justifyContent: "flex-start"}}>
                <Rate
                    allowClear={false}
                    allowHalf={true}
                    value={this.state.point}
                    onChange={(value) => {
                        if (CheckUserLogin()) {
                            /*  let fieldName = `course-${this.state.lessonDara.chapterId}-${this.props.userStore.userInfo.id}`;
                              console.log(fieldName, value)
                              window.localStorage.setItem(fieldName, value.toString());*/
                            this.submitRate(value);
                            this.setState({point: value});
                        }
                    }}/>
            </div>
        </div>
    }

    renderCheckModal = () => {
        const {isModalVisible} = this.state;
        return <Modal title={"登录提示"}
                      footer={
                          <div style={{display: "flex", justifyContent: "space-between"}}>
                              <Button type="primary"
                                      style={{background: "#3e84fd", border: "none", width: "1.6rem"}}
                                      onClick={() => {
                                          const datas = {
                                              course: 0,
                                              password: "123456",
                                              username: "thinktestAccount"
                                          };
                                          const exp = window.open();
                                          if (CheckUserLoginOnly()) {
                                              exp.location.href = `${this.state.lessonDara?.projUrl}?token=${this.props.userStore.accessToken}`;
                                          } else {
                                              AxioInstance.post(`${USER_LOGIN}`, JSON.stringify(datas)).then((resp: any) => {
                                                  exp.location.href = `${this.state.lessonDara?.projUrl}?token=${resp.access_token}`;
                                                  this.setState({isModalVisible: false});
                                              }).catch(e => {
                                                  console.error(e);
                                                  exp.close();
                                              });
                                          }
                                      }}>立即体验</Button>
                              <Button type="primary"
                                      style={{background: "#3e84fd", border: "none", width: "1.6rem"}}
                                      onClick={() => {
                                          if (CheckUserLoginByThink()) {
                                              window.open(`${this.state.lessonDara?.projUrl}?token=${this.props.userStore.accessToken}`)
                                          }
                                          this.setState({isModalVisible: false});
                                      }
                                      }>教学平台登录</Button>
                              <Button
                                  onClick={() => {
                                      this.setState({isModalVisible: false});
                                      this.props.userStore.setAccessToken(null);
                                      this.props.globalStore.SetLoginType(LoginType.ILAB);
                                      this.props.globalStore.updateShowLoginModalVisiable(true);
                                  }}
                                  type="primary"
                                  style={{background: "#3e84fd", border: "none", width: "1.6rem"}}
                              >实验空间登录</Button>

                          </div>
                      }
                      visible={isModalVisible}
                      onCancel={() => {
                          this.setState({isModalVisible: false});
                          this.props.globalStore.SetLoginType(LoginType.ILAB);
                      }}>
            <p>1.如果需要上传实验数据到实验空间(www.ilab-x.com)，请点击下方按钮"<span
                style={{color: "#FF2D2D"}}
            >实验空间登录</span>"</p>
            <p>2.如果只需要上传实验数据到教学平台，请点击下方按钮"<span
                style={{color: "#FF2D2D"}}
            >教学平台登录</span>"</p>
            <p>3.如果只是想体验一下实验，请点击下方按钮"<span
                style={{color: "#FF2D2D"}}
            >立即体验</span>"</p>
            {/*   <p>4.实验操作方法请点击查看"<span style={{color: "#3E84FD", cursor: "pointer"}} onClick={() => {
                this.setState({currentSelect: 4, isModalVisible: false});
            }}>使用教程</span>"</p>*/}
        </Modal>
    }

    renderTitle(props: any) {
        const {title} = props;
        return <div style={{
            width: "100%",
            height: "auto",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            marginBottom: "0.2rem"
        }}>
            <div style={{width: "37%", height: "0.02rem", background: "#cccccc"}}/>
            <div style={{fontSize: "0.22rem", textAlign: "center"}}>
                {title}
            </div>
            <div style={{width: "37%", height: "0.02rem", background: "#cccccc"}}/>
        </div>
    }

    private rendInfomation() {
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_information.png"/>
                    <span>实验信息</span>
                </div>
                <div style={{
                    display: "flex",
                    justifyContent: "space-between",
                    height: "1.5rem",
                    marginTop: "0.2rem"
                }}>
                    <div style={{width: "72%", height: "100%"}}>
                        <div className="course-info">
                            <div style={{width: "60%"}}>学分:{this.state.lessonDara.score / 100 || 0}</div>
                            <div style={{width: "40%"}}>学时:{this.state.lessonDara.duration || 0}</div>
                        </div>
                        <div className="course-info">
                            <div>教师:{(this.state.teachers && this.state.teachers.length > 0) ? this.state.teachers[0].name : "暂无"}</div>
                        </div>
                        <div className="course-info">
                            <div>学科:{this.state.lessonDara.typeName || ""}</div>
                        </div>
                    </div>
                    <div style={{height: "100%"}}>
                        <this.renderStar/>
                    </div>

                </div>
                <div style={{
                    width: "100%",
                    height: "1rem",
                    marginTop: "0.6rem",
                    display: "flex",
                    justifyContent: "space-between"
                }}>
                    <div style={{
                        //width: "33%",
                        //display: "flex",
                        //justifyContent: "space-between",
                        //flexDirection: "column",
                        //borderRight: "0.01rem solid #cccccc"
                    }}>
                        <div style={{fontSize: "0.24rem"}}>
                            累计访问量
                        </div>
                        <div style={{fontSize: "0.36rem", color: "#3e84fd"}}>
                            {this.state.record?.visitCount || 0}
                        </div>
                    </div>
                    <div style={{
                        // width: "33%",
                        display: "flex",
                        justifyContent: "space-between",
                        flexDirection: "column",
                        //borderRight: "0.01rem solid #cccccc"
                    }}>
                        <div style={{fontSize: "0.24rem"}}>
                            累计测验数
                        </div>
                        <div style={{fontSize: "0.36rem", color: "#3e84fd"}}>
                            {this.state.record?.expCount || 0}

                        </div>
                    </div>
                    <div style={{
                        //width: "33%",
                        display: "flex",
                        justifyContent: "space-between",
                        flexDirection: "column",
                    }}>
                        <div style={{fontSize: "0.24rem"}}>
                            累计学生数
                        </div>
                        <div style={{fontSize: "0.36rem", color: "#3e84fd"}}>
                            {this.state.record?.studentCount || 0}
                        </div>
                    </div>
                </div>
                <div style={{marginTop: "0.5rem"}}>
                    <div style={{marginBottom: "0.3rem"}}>
                        <this.renderTitle title={"实验介绍视频"}/>
                        <div
                            style={{
                                borderRadius: "0.14rem",
                                width: "80%",
                                height: "100%",
                                marginTop: "0.35rem",
                                margin: "0 auto"
                            }}
                        >
                            <DPlayer
                                options={{
                                    video: {
                                        url: SERVER_PICTURE_URL + this.state.lessonDara.introduceVideo,
                                        quality: [
                                            /* {
                                                 name: "高清",
                                                 url:
                                                     SERVER_PICTURE_URL + this.state.lessonDara.introduceVideo,
                                                 type: "hls",
                                             },*/
                                            {
                                                name: "超清",
                                                url:
                                                    SERVER_PICTURE_URL + this.state.lessonDara.introduceVideo,
                                                type: "normal",
                                            }
                                            ,
                                        ],
                                        defaultQuality: 0
                                        ,
                                    }

                                    ,
                                }
                                }
                            />
                        </div>
                    </div>
                    <div title="实验引导视频">
                        <this.renderTitle title={"实验引导视频"}/>
                        <div
                            style={{
                                borderRadius: "0.14rem",
                                width: "80%",
                                height: "100%",
                                marginTop: "0.35rem",
                                margin: "0 auto"
                            }}
                        >
                            <DPlayer
                                options={{
                                    video: {
                                        url: SERVER_PICTURE_URL + this.state.lessonDara.guideVideo,
                                        quality: [
                                            /* {
                                                 name: "高清",
                                                 url:
                                                     SERVER_PICTURE_URL + this.state.lessonDara.guideVideo,
                                                 type: "hls",
                                             },*/
                                            {
                                                name: "超清",
                                                url:
                                                    SERVER_PICTURE_URL + this.state.lessonDara.guideVideo,
                                                type: "normal",
                                            },
                                        ],
                                        defaultQuality: 0,
                                    },
                                }}
                            />
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    toAuth = () => {
        this.props.history.push("/authenticate");
    };

    private renderTeacherList() {
        console.log(this.state.teachers);
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon2_teacher.png"></img>
                    <span>团队介绍</span>
                </div>
                {this.state.teachers && this.state.teachers.length > 0 ? (
                    <List
                        itemLayout="horizontal"
                        dataSource={this.state.teachers}
                        renderItem={(item, index) => (
                            <List.Item>
                                <div
                                    className={this.state.expandID === index ? "teacher-containerShowAll" : "teacher-container"}>
                                    <div className="left-item-panel">
                                        <Avatar src={SERVER_PICTURE_URL + item.avatar}
                                                style={{width: "1rem", height: "1rem"}}/>
                                        {/* <div className="avatar-title">{item.name}</div> */}
                                    </div>
                                    <div style={{position: "relative", cursor: "pointer"}}
                                         onClick={() => {
                                             if (this.state.expandID === index) {
                                                 this.setState({expandID: -1, currentId: index})
                                             } else {
                                                 this.setState({currentId: this.state.expandID})
                                                 this.setState({expandID: index})
                                             }
                                         }}>
                                        <div className="avatar-title"
                                             style={{textAlign: "left"}}>{item.name}</div>
                                        <div className="Teacher-label"
                                             style={{textAlign: "left"}}>{item.titles}</div>
                                        <div id={"right-teacher-panel" + index}
                                             className={this.state.expandID === index ? "right-teacher-panelShowAll" : "right-teacher-panel"}>
                                            <div id={"textContent1" + index} style={{
                                                fontSize: "0.16rem",
                                                width: "100%",
                                                height: "auto",
                                                textAlign: "justify",
                                                color: "#666"
                                            }}>
                                                {item.description}
                                            </div>
                                        </div>
                                        <div style={{
                                            width: "100%",
                                            height: "0.32rem",
                                            display: "flex",
                                            position: "absolute",
                                            justifyContent: "center",
                                            color: "#666666",
                                            fontSize: "0.14rem",
                                            bottom: 0
                                        }}
                                        >
                                            {($(`#right-teacher-panel${index}`).outerHeight() < $(`#textContent1${index}`).outerHeight() || this.state.currentId === index) ?
                                                <div>
                                                    <img style={{
                                                        width: "0.14rem",
                                                        height: "0.14rem",
                                                        margin: "auto",
                                                        cursor: "pointer",
                                                        marginRight: "0.13rem",
                                                        marginTop: "-0.03rem"
                                                    }}
                                                         src={this.state.expandID === index ? "./ui/VRpage/shouqi.png" : "./ui/VRpage/zhankai.png"}
                                                    />{this.state.expandID === index ? "收起内容" : "展开内容"}
                                                </div> : <a></a>}
                                        </div>
                                    </div>
                                </div>
                            </List.Item>
                        )}
                    />
                ) : (
                    <Empty></Empty>
                )}
            </div>
        );
    }

    private renderExpGuide() {
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_1.png"></img>
                    <span>实验指南</span>
                </div>
                {" "}
                <div
                    className="rich-content"
                    dangerouslySetInnerHTML={{__html: setRichTextImage(this.state.lessonDara?.expGuide)}}
                />
            </div>
        );
    }

    private renderExpResource() {
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon5_material.png"></img>
                    <span>课程资源下载</span>
                </div>
                <ul className="download-ul">
                    {
                        this.state.docs.map((item, index) => {
                            return <li className="download-li" key={index}>
                                <span>{item.title}</span>
                                <div onClick={() => window.location.href = SERVER_PICTURE_URL + item.docPath}
                                     style={{fontSize: "0.18rem", lineHeight: "0.18rem", cursor: "pointer"}}>
                                    下载
                                    <img style={{marginLeft: "0.1rem", marginTop: "-0.05rem"}}
                                         src="./ui/VRpage/icon5_download.png"/>
                                </div>
                            </li>
                        })
                    }
                    <li className="download-li" key={"chrome"}>
                        <span>Chrome浏览器</span>
                        <div onClick={() => {
                            window.location.href = "https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B0EF7E0C4-E733-DD4A-5C47-374579BD454C%7D%26lang%3Dzh-CN%26browser%3D5%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe"
                        }}
                             style={{fontSize: "0.18rem", lineHeight: "0.18rem", cursor: "pointer"}}>
                            下载
                            <img style={{marginLeft: "0.1rem", marginTop: "-0.05rem"}}
                                 src="./ui/VRpage/icon5_download.png"/>
                        </div>
                    </li>
                    <li className="download-li" key={"firefox"}>
                        <span>FireFox浏览器</span>
                        <div onClick={() => {
                            window.location.href = "https://download-ssl.firefox.com.cn/releases-sha2/stub/official/zh-CN/Firefox-latest.exe"
                        }}
                             style={{fontSize: "0.18rem", lineHeight: "0.18rem", cursor: "pointer"}}>
                            下载
                            <img style={{marginLeft: "0.1rem", marginTop: "-0.05rem"}}
                                 src="./ui/VRpage/icon5_download.png"/>
                        </div>
                    </li>
                </ul>
            </div>
        );
    }

    private renderStudyRecord() {
        const columns = [
            {
                title: "实验名称",
                dataIndex: "expName",
                width: "15%",
                ellipsis: true,
                key: "expName",
            },
            {
                title: "实验状态",
                dataIndex: "status",
                key: "status",
                width: "15%",
                render: (a, r) => {
                    switch (r.status) {
                        case 1:
                        case 2:
                            return "未完成"
                        case 3:
                            return "已完成"
                    }
                    return ""
                }
            },
            {
                title: "实验成绩",
                dataIndex: "score",
                key: "score",
                width: "15%",
                render: (record) => record || "---"
            },
            {
                title: "开始时间",
                width: "20%",
                ellipsis: true,
                render: (record) =>
                    <span>{record.startTime ? moment(record.startTime).format("YYYY-MM-DD HH:mm:ss") : "未开始"}</span>
            },
            {
                title: "结束时间",
                width: "20%",
                ellipsis: true,
                render: (record) =>
                    <span>{record.endTime ? moment(record.endTime).format("YYYY-MM-DD HH:mm:ss") : "---"}</span>
            },
            {
                title: "实验用时",
                dataIndex: "timeUsed",
                key: "timeUsed",
                width: "15%",
                render: (a, r) => {
                    if (r.endTime) {
                        const timed = moment(r.endTime).diff(moment(r.startTime), 'seconds')
                        return FormatTime(timed);
                    } else {
                        return "---";
                    }
                }
            },
        ];
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_1.png"></img>
                    <span>学习记录</span>
                </div>
                <Table
                    style={{marginTop: "0.4rem"}}
                    bordered
                    columns={columns}
                    rowKey={record => record.id}
                    dataSource={this.state.studyRecord.records}
                    pagination={{
                        total: this.state.studyRecord.total,
                        current: this.state.studyRecord.current,
                        onChange: this.onRecordChange,
                        showSizeChanger: false
                    }}
                />
            </div>
        );
    }

    private onRecordChange = (page, pageSize) => {
        this.getStudyRecord(page, pageSize, this.state.lessonDara.id)
    }

    private g1Ele: HTMLElement;

    private renderStats() {
        let time = null;
        if (this.state.time.hasOwnProperty("total")) {
            const total = Number.parseInt(this.state.time.total) / 60;
            time = Math.ceil(total);
        }
        console.log(time);
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_1.png"></img>
                    <span>数据分析</span>
                </div>
                <div>
                    <Row gutter={16} style={{height: "1.5rem", marginTop: "0.4rem"}}>
                        <Col span={6}>
                            <div
                                className="stat-block"
                                style={{background: "rgb(88, 162, 247)"}}
                            >
                                <Statistic title="用户总数量" value={this.state.record?.visitCount || 0}/>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div
                                className="stat-block"
                                style={{background: "rgb(254, 192, 57)"}}
                            >
                                <Statistic title="实验总次数" value={this.state.record?.expCount || 0}/>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div
                                className="stat-block"
                                style={{background: "rgb(82, 193, 246)"}}
                            >
                                <Statistic title="实验总时长" value={time || 0}/>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div
                                className="stat-block"
                                style={{background: "rgb(252, 98, 96)"}}
                            >
                                <Statistic title="总访问人数" value={this.state.record?.studentCount || 0}/>
                            </div>
                        </Col>
                    </Row>
                    <Divider></Divider>
                    <Row gutter={16}>
                        <Col span={16}>
                            <div className="stat-graph-block">
                                <div>用户使用时长分布</div>
                                <Divider className="stat-divide"></Divider>
                                <div id="g1Ele" style={{height: "5rem"}}></div>
                            </div>
                        </Col>
                        {/*   <Col span={8}>
                            <div className="stat-graph-block">
                                <div>用户数量统计分析</div>
                                <Divider className="stat-divide"></Divider>
                                <div id="g2Ele" style={{height: "5rem"}}></div>
                            </div>
                        </Col>*/}
                        <Col span={8}>
                            <div className="stat-graph-block">
                                <div>用户成绩统计分析</div>
                                <Divider className="stat-divide"></Divider>
                                <div id="g3Ele" style={{height: "5rem"}}></div>
                            </div>
                        </Col>
                    </Row>
                </div>
            </div>
        );
    }

    private renderDeviceRequire() {
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_1.png"></img>
                    <span>设备要求</span>
                </div>
                <div
                    className="rich-content"
                    dangerouslySetInnerHTML={{
                        __html: setRichTextImage(this.state.lessonDara?.deviceRequire),
                    }}
                    style={{marginTop: "0.1rem"}}
                ></div>
            </div>
        );
    }

    private renderCourseFeature() {
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_1.png"></img>
                    <span>实验特色</span>
                </div>
                <div
                    className="rich-content"
                    dangerouslySetInnerHTML={{
                        __html: setRichTextImage(this.state.lessonDara?.expFeature),
                    }}
                    style={{marginTop: "0.1rem"}}
                />
            </div>
        );
    }

    /*互动评论*/
    private renderQAQ() {
        const comments = this.props.commentStore.comments;
        console.log(comments)
        const user = this.props.userStore.userInfo;
        return (
            <div>
                <div className="course-title">
                    <img src="./ui/VRpage/icon2_subject.png"></img>
                    <span>互动问答</span>
                </div>
                <div className={"course-comment-head"}>
                    <CommentBox/>
                </div>
                <div className={"course-comment-body"}>
                    {
                        comments.length > 0 ?
                            comments.map((element, index) => {
                                return <CommentItem key={element.id} comment={element} reply={null}>
                                    {
                                        this.deserializeCommentTree(element)
                                    }
                                </CommentItem>
                            })
                            : null
                    }
                </div>
            </div>
        );
    }

    private deserializeCommentTree = (node: any) => {
        if (node.replies.length > 0) {
            return node.replies.map((element, index) => {
                if (element.replies.length > 0) {
                    return <div key={element.id}>
                        <CommentItem key={element.id} comment={element} reply={node.nickname}>
                        </CommentItem>
                        {
                            this.deserializeCommentTree(element)
                        }
                    </div>
                } else {
                    return <CommentItem key={element.id} comment={element} reply={node.nickname}>
                    </CommentItem>
                }

            })
        }
        return null;
    }

    private renderServicePlan() {
        return (
            <div className="container" style={{background: "#fff"}}>
                <div className="course-title">
                    <img src="./ui/VRpage/icon_1.png"></img>
                    <span>服务计划</span>
                </div>
                {this.state.lessonDara?.servicePlan ? (
                    <div
                        className="rich-content"
                        dangerouslySetInnerHTML={{
                            __html: setRichTextImage(this.state.lessonDara?.servicePlan),
                        }}
                        style={{marginTop: "0.1rem"}}
                    ></div>
                ) : (
                    <Empty></Empty>
                )}
            </div>
        );
    }

    private async waitForRenderGraph() {
        var ele1 = await $.when("g1Ele");
        //清空图表
        $("#g1Ele").empty();
        $("#g3Ele").empty();
        const {time, score} = this.state;
        const data = [
            {type: '0-10分钟', value: time["0-10"]},
            {type: '10-30分钟', value: time["10-30"]},
            {type: '30-50分钟', value: time["30-50"]},
            {type: '50-70分钟', value: time["50-70"]},
            {type: '70-90分钟', value: time["70-90"]},
            {type: '90分钟以上', value: time["90-1000"]},
        ];

        const chart = new Chart({
            container: 'g1Ele',
            autoFit: true,
            height: 500,
            padding: [50, 20, 50, 20],
        });
        chart.data(data);
        chart.scale('value', {
            alias: '使用时长(分钟)',
        });

        chart.axis('type', {
            tickLine: {
                alignTick: false,
            },
        });
        chart.axis('value', false);

        chart.tooltip({
            showMarkers: false,
        });
        chart.interval().position('type*value');
        chart.interaction('element-active');

        // 添加文本标注
        data.forEach((item) => {
            chart
                .annotation()
                .text({
                    position: [item.type, item.value],
                    content: item.value,
                    style: {
                        textAlign: 'center',
                    },
                    offsetY: -30,
                });
            /* .text({
              position: [item.type, item.value],
              content: (item.percent * 100).toFixed(0) + '%',
              style: {
                  textAlign: 'center',
              },
              offsetY: -12,
          });*/
        });
        chart.render();
        let sum = 0;
        for (let item in score) {
            sum += score[item];
        }
        const data3 = [
            {item: ">90", count: score["90-100"] || 0, percent: score["90-100"] / sum},
            {item: ">80", count: score["80-90"] || 0, percent: score["80-90"] / sum},
            {item: ">70", count: score["70-80"] || 0, percent: score["70-80"] / sum},
            {item: ">60", count: score["60-70"] || 0, percent: score["60-70"] / sum},
            {item: "<60", count: score["0-60"] || 0, percent: score["0-60"] / sum},
        ];
        const chart3 = new Chart({
            container: "g3Ele",
            autoFit: true,
            height: 500,
        });
        chart3.data(data3);
        chart3.scale("percent", {
            formatter: (val) => {
                val = val * 100 + "%";
                return val;
            },
        });
        chart3.coordinate("theta", {
            radius: 0.75,
            innerRadius: 0.6,
        });
        chart3.tooltip({
            showTitle: false,
            showMarkers: false,
            itemTpl:
                '<li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>',
        });
        // 辅助文本
        chart3
            .annotation()
            .text({
                position: ["50%", "50%"],
                content: "",
                style: {
                    fontSize: 14,
                    fill: "#8c8c8c",
                    textAlign: "center",
                },
                offsetY: -20,
            })
            .text({
                position: ["50%", "50%"],
                content: "",
                style: {
                    fontSize: 20,
                    fill: "#8c8c8c",
                    textAlign: "center",
                },
                offsetX: -10,
                offsetY: 20,
            })
            .text({
                position: ["50%", "50%"],
                content: "",
                style: {
                    fontSize: 14,
                    fill: "#8c8c8c",
                    textAlign: "center",
                },
                offsetY: 20,
                offsetX: 20,
            });
        chart3
            .interval()
            .adjust("stack")
            .position("percent")
            .color("item")
            .tooltip("item*percent", (item, percent) => {
                percent = Math.trunc(percent * 100) + "%";
                return {
                    name: item,
                    value: percent,
                };
            });
        chart3.legend({position: "top", flipPage: false});
        chart3.interaction("element-active");

        chart3.render();
    }

    randomNum(minNum, maxNum) {
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum);
    }

    Banner = () => {
        return <div>
            <img style={{
                width: "100%",
                height: this.state.lessonDara?.expImg === "" ? "10rem" : "auto",
            }}
                 src={SERVER_PICTURE_URL + this.state.lessonDara?.expImg}
            />
            <div style={{position: "relative", top: "-2.8rem", height: 0, textAlign: 'center'}}>
                <button className="start-exam-btn"
                        onMouseEnter={() => {
                            let num = this.randomNum(5, 30);
                            // $("#wait").fadeIn();
                            this.setState({isWait: true, waitNum: num});
                        }}
                        onMouseLeave={() => {
                            this.setState({isWait: false});
                            // $("#wait").fadeOut();
                        }}
                        onClick={() => {
                            if (CheckUserLoginOnly()) {
                                const exp = window.open();
                                AxioInstance.get(`${GET_CHECK_ILAB_LOGIN}/${this.props.commentStore.courseId}`).then((resp: any) => {
                                    if (resp) {
                                        exp.location.href = `${this.state.lessonDara?.projUrl}?token=${this.props.userStore.accessToken}`;
                                    } else {
                                        this.setState({isModalVisible: true});
                                    }
                                }).catch((e) => {
                                    if (CheckUserLoginByThink()) {
                                        exp.location.href = `${this.state.lessonDara?.projUrl}?token=${this.props.userStore.accessToken}`;
                                    } else {
                                        this.setState({isModalVisible: true});
                                        exp.close();
                                        // console.error(e);
                                    }
                                });
                            } else {
                                this.setState({isModalVisible: true});
                            }

                        }
                        }>
                    开始实验
                </button>
                <div id="wait" className="wait-msg"> {
                    this.state.isWait ? `最大并发数:200  在线人数:${this.state.waitNum}  当前无需排队` :
                        `请使用谷歌Chrome、火狐FireFox、微软Edge浏览器进行实验，可在下方实验资源中下载安装对应浏览器`
                }</div>
                {/*  {
                    this.state.visible ?  : null
                }*/}
            </div>

        </div>
    }

    setWebViewImage(star) {
        var head = "<head>"
            + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
            + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
            + "<style>table{max-width: 100%; width:auto; height:auto;}</style>"
            + "</head>";
        return "<html>" + head + "<body>" + star + "</body></html>";

    }

    render() {
        const data = [
            {
                title: "实验信息",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 0
                                ? "./ui/VRpage/icon_information_s.png"
                                : "./ui/VRpage/icon_information_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.rendInfomation.bind(this),
            },
            {
                title: "项目介绍",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 1
                                ? "./ui/VRpage/icon1_project_s.png"
                                : "./ui/VRpage/icon1_project_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.rendDescription.bind(this),
            },
            {
                title: "团队介绍",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 2
                                ? "./ui/VRpage/icon2_teacher_s.png"
                                : "./ui/VRpage/icon2_teacher_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderTeacherList.bind(this),
            },
            {
                title: "实验特色",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 3
                                ? "./ui/VRpage/icon3_characteristic_s.png"
                                : "./ui/VRpage/icon3_characteristic_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderCourseFeature.bind(this),
            },

            {
                title: "实验指南",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 4
                                ? "./ui/VRpage/icon4_guide_s.png"
                                : "./ui/VRpage/icon4_guide_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderExpGuide.bind(this),
            },
            {
                title: "实验资源",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 5
                                ? "./ui/VRpage/icon5_resources_s.png"
                                : "./ui/VRpage/icon5_resources_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderExpResource.bind(this),
            },
            {
                title: "设备支持",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 6
                                ? "./ui/VRpage/icon6_equipment_s.png"
                                : "./ui/VRpage/icon6_equipment_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderDeviceRequire.bind(this),
            },
            {
                title: "服务计划",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 7
                                ? "./ui/VRpage/icon7_service_s.png"
                                : "./ui/VRpage/icon7_service_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderServicePlan.bind(this),
            }, {
                title: "互动问答",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 8
                                ? "./ui/CoursePage/icon4_interaction_s.png"
                                : "./ui/CoursePage/icon4_interaction_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderQAQ.bind(this),
            },
            {
                title: "学习记录",
                onClick: () => {
                },
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 9
                                ? "./ui/VRpage/icon8_learn_s.png"
                                : "./ui/VRpage/icon8_learn_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderStudyRecord.bind(this),
            },
            {
                title: "数据分析",
                onClick: this.waitForRenderGraph.bind(this),
                icon: (
                    <img
                        src={
                            this.state.currentSelect == 10
                                ? "./ui/VRpage/icon9_data_s.png"
                                : "./ui/VRpage/icon9_data_n.png"
                        }
                        className="nav-icon"
                    />
                ),
                renderPanel: this.renderStats.bind(this),
            },
        ];
        return (
            <div>
                {this.state.lessonDara ? (
                    <div className="container" style={{background: "#f5f5f5"}}>
                        <this.Banner/>
                        <div
                            style={{
                                display: "flex",
                                flexDirection: "row",
                                margin: "0.3rem auto 0rem ",
                                minHeight: "8rem",
                                width: "14rem",
                                position: "relative",
                                background: "#f5f5f5",
                                zIndex: 5,
                            }}
                        >
                            <div
                                className="left-panel"
                                style={{
                                    height: "100%",
                                    background: "#fff"
                                }}>
                                {data.map((item, index) => {
                                    return (
                                        <div
                                            key={index}
                                            className={`left-nav-btn nav-item ${this.state.currentSelect === index ? "active" : ""
                                            }`}
                                            onClick={() => {
                                                this.setState({currentSelect: index});
                                                item.onClick.bind(this)();
                                            }}
                                        >
                                            {item.icon}
                                            <a>{item.title}</a>
                                        </div>
                                    );
                                })}
                            </div>
                            <div className="right-panel"
                                 style={{margin: "0", marginLeft: "0.2rem", marginBottom: "0.3rem"}}
                            >
                                <div style={{margin: "0.33rem 1.14rem 0.33rem 0.68rem"}}>
                                    {data[this.state.currentSelect].renderPanel()}
                                </div>
                            </div>
                        </div>
                    </div>
                ) : (
                    <div>
                        <Spin></Spin>
                    </div>
                )}
                <AuthenticateModal Confirm={this.toAuth.bind(this)}/>
                <this.renderCheckModal/>
            </div>
        );
    }
}

export enum RecordState {
    "未完成" = 1,
    "进行中",
    "已完成"
}

export default VRExp;
